package sy.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
/**
 * 捷顺停车场辅助类
 * 集成了相关业务逻辑接口
 * @author xieyuanqiu
 */
public class JSInterface {
/*	private static final String cno = "ypttset"; 
	private static final String usr = "ypttest";
	private static final String server = "http://218.17.23.98:8089";*/
	private static final String psw = "123456"; 
	private static final String cno = "ypt-test"; 
	private static final String usr = "ypt-test"; 
	private static final String server = "http://202.105.104.105:8089";//外网地址
	
	private static String sendPostJX(String url, String params, String sn) {  
		String result = "";
		BufferedReader in = null;// 读取响应输入流  
		PrintWriter out = null;  
		try {  
			// 创建URL对象  
			java.net.URL connURL = new java.net.URL(url);  
			// 打开URL连接  
			java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL  
					.openConnection();  
			// 设置通用属性  
			httpConn.setRequestProperty("Accept", "*/*");  
			httpConn.setRequestProperty("Connection", "Keep-Alive");  
			httpConn.setRequestProperty("User-Agent",  
					"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");  
			httpConn.setRequestProperty("sn", sn);
			// 设置POST方式  
			httpConn.setDoInput(true);  
			httpConn.setDoOutput(true);  
			// 获取HttpURLConnection对象对应的输出流  
			out = new PrintWriter(httpConn.getOutputStream());  
			// 发送请求参数  
			out.write(params);  
			// flush输出流的缓冲  
			out.flush();  
			// 定义BufferedReader输入流来读取URL的响应，设置编码方式  
			in = new BufferedReader(new InputStreamReader(httpConn  
					.getInputStream(), "UTF-8"));  
			String line;  
			// 读取返回的内容  
			while ((line = in.readLine()) != null) {  
				result += line;  
			}  
		} catch (Exception e) {  
			e.printStackTrace();  
		} finally {  
			try {  
				if (out != null) {  
					out.close();  
				}  
				if (in != null) {  
					in.close();  
				}  
			} catch (IOException ex) {  
				ex.printStackTrace();  
			}  
		} 
		return result;  
	}
	
	/**
	 * 登录获取token
	 * @Title: getToken
	 * @Description: TODO
	 * @param: @return     
	 * @return: String     
	 * @author:  xieyuanqiu
	 * @date: 2017年9月17日 下午5:30:58
	 * @throws
	 */
	public static String getAccessToken(){
		String token = "";
		Map<String, String> param = new HashMap<String, String>();
    	param.put("cno", cno);
    	param.put("usr", usr);
    	param.put("psw", psw);
    	String result = sendPostJX(server+"/login", JSON.toJSONString(param),"");
    	JSONObject obj = JSONObject.parseObject(result);
    	int resultCode = Integer.parseInt(obj.getString("resultCode"));
    	System.out.println(result);
    	if(resultCode==0){
    		token = obj.getString("token");
    	}
		return token;
	}
	
	/**
	 * 根据车场ID，设备ID,时间段，状态查找出入场记录
	 * @Title: getEntryLog
	 * @Description: TODO
	 * @param: @param itemId
	 * @param: @param equipmentId
	 * @param: @param state
	 * @param: @param startTime
	 * @param: @param endTime
	 * @param: @param token
	 * @param: @return     
	 * @return: String     
	 * @author:  xieyuanqiu
	 * @date: 2017年9月18日 下午2:30:50
	 * @throws
	 */
	public static String getEntryLog(String itemId,String equipmentId, String state, String startTime, String endTime, String token){
		String result = "";
		/**********************构造业务参数p***************************/
		Map<String,Object> p = new HashMap<String,Object>();
		p.put("requestType", "DATA");
		List<Map<String,Object>> dataItems = new ArrayList<Map<String,Object>>();
		Map<String,Object> dataItem = new HashMap<String,Object>();
		dataItem.put("itemId", itemId);
		dataItem.put("equipmentId", equipmentId);
		dataItem.put("state", state);
		dataItem.put("startTime", startTime);
		dataItem.put("endTime", endTime);
		dataItems.add(dataItem);
		p.put("dataItems", dataItems);
		/************************构造签名参数*******************************/
		Map<String,Object> signParams = new HashMap<String,Object>();
		signParams.put("cno", cno);
		signParams.put("tn", token);
		signParams.put("p", p);

		String str = JSON.toJSONString(signParams);//签名参数
		/************生成签名:最终值要大写***************/
		String snLowerCase = Encrypt.md5(str+"sign");
		String sn = snLowerCase.toUpperCase();
		
		Map<String, Object> params = new HashMap<String, Object>();

		params.put("cno", cno);
		params.put("tn", token);
		params.put("p", p);
		
		result = sendPostJX(server + "/park/record", JSON.toJSONString(params), sn);
		return result;
	}
	/**
	 * 根据出入场记录找图片
	 * @Title: getImagesByEntryLog
	 * @Description: TODO
	 * @param: @param itemId
	 * @param: @param state
	 * @param: @param token
	 * @param: @return     
	 * @return: String     
	 * @author:  xieyuanqiu
	 * @date: 2017年9月25日 下午3:07:16
	 * @throws
	 */
	public static String getImagesByEntryLog(String itemId,String state,String token){
		String result = "";
		/**********************构造业务参数p***************************/
		Map<String,Object> p = new HashMap<String,Object>();
		p.put("requestType", "DATA");
		List<Map<String,Object>> dataItems = new ArrayList<Map<String,Object>>();
		Map<String,Object> dataItem = new HashMap<String,Object>();
		dataItem.put("itemId", itemId);
		dataItem.put("state", state);
		dataItems.add(dataItem);
		p.put("dataItems", dataItems);
		/************************构造签名参数*******************************/
		Map<String,Object> signParams = new HashMap<String,Object>();
		signParams.put("cno", cno);
		signParams.put("tn", token);
		signParams.put("p", p);

		String str = JSON.toJSONString(signParams);//签名参数
		/************生成签名:最终值要大写***************/
		String snLowerCase = Encrypt.md5(str+"sign");
		String sn = snLowerCase.toUpperCase();
		
		Map<String, Object> params = new HashMap<String, Object>();

		params.put("cno", cno);
		params.put("tn", token);
		params.put("p", p);
		
		result = sendPostJX(server + "/park/photo", JSON.toJSONString(params), sn);
		return result;
	}
	
	/**
	 * 中海系统调用平台统一接口查找最近的车牌及图片
	 * @Title: getImagesByEntryLog
	 * @Description: TODO
	 * @param: @param itemId
	 * @param: @param equipmentId
	 * @param: @param state
	 * @param: @param token
	 * @param: @return     
	 * @return: String     
	 * @author:  xieyuanqiu
	 * @date: 2017年9月27日 上午10:01:46
	 * @throws
	 */
	public static String getLatestInfo(String itemId,String equipmentId,String state,String token){
		String result = "";
		/**********************构造业务参数p***************************/
		Map<String,Object> p = new HashMap<String,Object>();
		p.put("requestType", "DATA");
		List<Map<String,Object>> dataItems = new ArrayList<Map<String,Object>>();
		Map<String,Object> dataItem = new HashMap<String,Object>();
		dataItem.put("itemId", itemId);
		dataItem.put("equipmentId", equipmentId);
		dataItem.put("state", state);
		dataItems.add(dataItem);
		p.put("dataItems", dataItems);
		/************************构造签名参数*******************************/
		Map<String,Object> signParams = new HashMap<String,Object>();
		signParams.put("cno", cno);
		signParams.put("tn", token);
		signParams.put("p", p);

		String str = JSON.toJSONString(signParams);//签名参数
		/************生成签名:最终值要大写***************/
		String snLowerCase = Encrypt.md5(str+"sign");
		String sn = snLowerCase.toUpperCase();
		
		Map<String, Object> params = new HashMap<String, Object>();

		params.put("cno", cno);
		params.put("tn", token);
		params.put("p", p);
		
		result = sendPostJX(server + "/park/carNumber", JSON.toJSONString(params), sn);
		return result;
	}
	
	
	/**
	 * 中海系统调用平台统一接口下发设备操控指令
	 * 打开：command=1
	 * 关闭：command=0
	 * @Title: operateEquipment
	 * @Description: TODO
	 * @param: @param itemId
	 * @param: @param state
	 * @param: @param token
	 * @param: @return     
	 * @return: String     
	 * @author:  xieyuanqiu
	 * @date: 2017年9月26日 下午5:47:55
	 * @throws
	 */
	public static String operateEquipment(String itemId,String personId,String command,String token){
		String result = "";
		/**********************构造业务参数p***************************/
		Map<String,Object> p = new HashMap<String,Object>();
		p.put("requestType", "DATA");
		List<Map<String,Object>> dataItems = new ArrayList<Map<String,Object>>();
		Map<String,Object> dataItem = new HashMap<String,Object>();
		dataItem.put("itemId", itemId);
		dataItem.put("personId", personId);
		dataItem.put("command", command);
		dataItems.add(dataItem);
		p.put("dataItems", dataItems);
		/************************构造签名参数*******************************/
		Map<String,Object> signParams = new HashMap<String,Object>();
		signParams.put("cno", cno);
		signParams.put("tn", token);
		signParams.put("p", p);

		String str = JSON.toJSONString(signParams);//签名参数
		/************生成签名:最终值要大写***************/
		String snLowerCase = Encrypt.md5(str+"sign");
		String sn = snLowerCase.toUpperCase();
		
		Map<String, Object> params = new HashMap<String, Object>();

		params.put("cno", cno);
		params.put("tn", token);
		params.put("p", p);
		
		result = sendPostJX(server + "/equipment/operator", JSON.toJSONString(params), sn);
		return result;
	}
	
	/**
	 * 中海系统调用平台统一接口进行自己的对外接口注册
	 * @Title: registerService
	 * @Description: TODO
	 * @param: @param serviceKey
	 * @param: @param serviceUrl
	 * @param: @param serviceDesc
	 * @param: @param token
	 * @param: @return     
	 * @return: String     
	 * @author:  xieyuanqiu
	 * @date: 2017年9月26日 下午6:05:23
	 * @throws
	 */
	public static String registerService(String serviceKey,String serviceUrl,String serviceDesc,String token){
		String result = "";
		/**********************构造业务参数p***************************/
		Map<String,Object> p = new HashMap<String,Object>();
		p.put("requestType", "DATA");
		List<Map<String,Object>> dataItems = new ArrayList<Map<String,Object>>();
		Map<String,Object> dataItem = new HashMap<String,Object>();
		dataItem.put("serviceKey", serviceKey);
		dataItem.put("serviceUrl", serviceUrl);
		dataItem.put("serviceDesc", serviceDesc);
		dataItems.add(dataItem);
		p.put("dataItems", dataItems);
		/************************构造签名参数*******************************/
		Map<String,Object> signParams = new HashMap<String,Object>();
		signParams.put("cno", cno);
		signParams.put("tn", token);
		signParams.put("p", p);

		String str = JSON.toJSONString(signParams);//签名参数
		/************生成签名:最终值要大写***************/
		String snLowerCase = Encrypt.md5(str+"sign");
		String sn = snLowerCase.toUpperCase();
		
		Map<String, Object> params = new HashMap<String, Object>();

		params.put("cno", cno);
		params.put("tn", token);
		params.put("p", p);
		result = sendPostJX(server + "/registerService", JSON.toJSONString(params), sn);
		return result;
	}
	
	
	/**
	 * 推送敏感事件到中海平台
	 * @Title: pushSensitiveEvent
	 * @Description: TODO
	 * @param: @return     
	 * @return: String     
	 * @author:  xieyuanqiu
	 * @date: 2017年9月25日 下午3:38:33
	 * @throws
	 */
/*	public static String pushSensitiveEvent(String eventName,String eventTime,String equipmentName,String systemName,String systemId,String token){
		String result = "";
		*//**********************构造业务参数p***************************//*
		Map<String,Object> p = new HashMap<String,Object>();
		p.put("requestType", "DATA");
		List<Map<String,Object>> dataItems = new ArrayList<Map<String,Object>>();
		Map<String,Object> dataItem = new HashMap<String,Object>();
		dataItem.put("eventName", eventName);
		dataItem.put("eventTime", eventTime);
		dataItem.put("equipmentName", equipmentName);
		dataItem.put("systemName", systemName);
		dataItem.put("systemId", systemId);
		dataItems.add(dataItem);
		p.put("dataItems", dataItems);
		*//************************构造签名参数*******************************//*
		Map<String,Object> signParams = new HashMap<String,Object>();
		signParams.put("cno", cno);
		signParams.put("tn", token);
		signParams.put("p", p);

		String str = JSON.toJSONString(signParams);//签名参数
		*//************生成签名:最终值要大写***************//*
		String snLowerCase = Encrypt.md5(str+"sign");
		String sn = snLowerCase.toUpperCase();
		
		Map<String, Object> params = new HashMap<String, Object>();

		params.put("cno", cno);
		params.put("tn", token);
		params.put("p", p);
		
		result = sendPostJX("http://202.105.104.105:8006/ssh/jsRegister/sensitive/event", JSON.toJSONString(params), sn);
		return result;
	}*/
	public static void main(String[] args){
		//currentToken = 232cf271d9804aa788dfd29060bf3a41
		//System.out.println(getAccessToken());
		String result = "";
		String token = "263cc36b894445b78334a0dac492a9d5";
		/***************************根据出入场记录查找图片（成功）**********************************/
/*		String itemId = "be6c568c7bfa421aa35db363c01c3220";
		String state = "in";
		result = getImagesByEntryLog(itemId,state,token);
		//System.out.println(result);
		JSONObject obj = JSONObject.parseObject(result);
		String dataItems = obj.getString("dataItems");
		JSONArray arr = JSONArray.parseArray(dataItems);
		for(int i = 0; i<arr.size(); i++){
			JSONObject obj1 = arr.getJSONObject(i);
			String photos = obj1.getString("photos");
			JSONArray photosArr = JSONArray.parseArray(photos);
			Base64.decodeBase64ToImage(photosArr.getString(0), "D:\\\\", "test.png");
			//System.out.println(photosArr.size());
			for(int j = 0; j<photosArr.size(); j++){
				String base64Str = photosArr.getString(j);
				String str = Base64.getFromBASE64(base64Str);
				System.out.println(str);
			}
		}*/
		
		/************************************捷顺平台推送敏感事件到中海平台*********************************************/
		/**
		 * 1.先通过第三方接口进行注册中海已有的推送事件接口（已调试成功）
		 * 2.捷顺平台再调用推送服务
		 */
/*		String serviceKey = "SENSITIVE";
		String serviceUrl = "http://202.105.104.105:8006/ssh/jsRegister/sensitive/event";
		String serviceDesc = "敏感事件接口注册";
		result = registerService(serviceKey, serviceUrl, serviceDesc, getAccessToken());
		System.out.println(result);*/
		
		
/*		String eventName = "车辆入场";
		String eventTime = "2017-09-25 15:40:25";
		String equipmentName = "I-Cloud系列";
		String systemName = "test";
		String systemId = "6c7fb5de82694ade885ab07883738670";
		result = pushSensitiveEvent(eventName, eventTime, equipmentName, systemName, systemId, "232cf271d9804aa788dfd29060bf3a41");
		System.out.println(result);*/
		
		
		/***************************************中海系统调用平台统一接口下发设备操控指令（成功）**********************************/
		String itemId = "311f0c5694f64789bccc56327db813fd";
		String personId = "13bf113562624ae9aa6567d4bc59b727";
		String command = "1";
		result = operateEquipment(itemId, personId, command, token);
		System.out.println(result);
		 
		
		/***************************中海系统调用平台统一接口查找最近的车牌及图片**********************************/
/*		String itemId = "56d504d899f111e7a5f678acc0a48195";
		String equipmentId = "311f0c5694f64789bccc56327db813fd";
		String state = "in";
		result = getLatestInfo(itemId, equipmentId, state, token);
		System.out.println(result);*/
	}
}
